{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\IDEA\\Anaconda3\\envs\\py37\\lib\\site-packages\\h5py\\__init__.py:72: UserWarning: h5py is running against HDF5 1.10.2 when it was built against 1.10.3, this may cause problems\n",
      "  '{0}.{1}.{2}'.format(*version.hdf5_built_version_tuple)\n",
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'2.2.4'"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import keras\n",
    "keras.__version__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import os, shutil\n",
    "original_dir= #place here direction to directory with images"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# The directory where we will\n",
    "# store our smaller dataset\n",
    "base_dir = #create a folder named \"conv\" in the directory\n",
    "os.mkdir(base_dir)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Directories for our training,\n",
    "# validation and test splits\n",
    "train_dir = os.path.join(base_dir, 'train')\n",
    "os.mkdir(train_dir)\n",
    "validation_dir = os.path.join(base_dir, 'validation')\n",
    "os.mkdir(validation_dir)\n",
    "test_dir = os.path.join(base_dir, 'test')\n",
    "os.mkdir(test_dir)\n",
    "\n",
    "#Create:\n",
    "# A directory with our training pictures of cut marks on defleshed bones\n",
    "train_nm_dir = os.path.join(train_dir, 'NM')\n",
    "os.mkdir(train_nm_dir)\n",
    "\n",
    "# Directory with our training pictures of cut marks on fleshed bones\n",
    "train_wm_dir = os.path.join(train_dir, 'WM')\n",
    "os.mkdir(train_wm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on defleshed bones\n",
    "validation_nm_dir = os.path.join(validation_dir, 'NM')\n",
    "os.mkdir(validation_nm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on fleshed bones\n",
    "validation_wm_dir = os.path.join(validation_dir, 'WM')\n",
    "os.mkdir(validation_wm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on defleshed bones\n",
    "test_nm_dir = os.path.join(test_dir, 'NM')\n",
    "os.mkdir(test_nm_dir)\n",
    "\n",
    "# Directory with our validation pictures of cut marks on fleshed bones\n",
    "test_wm_dir = os.path.join(test_dir, 'WM')\n",
    "os.mkdir(test_wm_dir)\n",
    "\n",
    "# Copy first CM images to train_nm_dir\n",
    "fnames = ['NM.{}.bmp'.format(i) for i in range(70)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(train_nm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "\n",
    "# Copy next CM images to validation_nm_dir\n",
    "fnames = ['NM.{}.bmp'.format(i) for i in range(70, 85)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(validation_nm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "# Copy next CM images to test_nm_dir\n",
    "fnames = ['NM.{}.bmp'.format(i) for i in range(85, 100)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(test_nm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "# Copy first CM images to train_wm_dir\n",
    "fnames = ['WM.{}.bmp'.format(i) for i in range(91)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(train_wm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "# Copy next CM images to validation_wm_dir\n",
    "fnames = ['WM.{}.bmp'.format(i) for i in range(91, 110)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(validation_wm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n",
    "# Copy next CM images to test_wm_dir\n",
    "fnames = ['WM.{}.bmp'.format(i) for i in range(110, 130)]\n",
    "for fname in fnames:\n",
    "    src = os.path.join(original_dir, fname)\n",
    "    dst = os.path.join(test_wm_dir, fname)\n",
    "    shutil.copyfile(src, dst)\n",
    "    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from keras import layers\n",
    "from keras import models\n",
    "\n",
    "#height, width, channels\n",
    "model = models.Sequential()\n",
    "model.add(layers.Conv2D(32, (3, 3), activation='relu',\n",
    "                        input_shape=(80, 400, 3)))#cambiar 1 a 3 si es color\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(64, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Conv2D(128, (3, 3), activation='relu'))\n",
    "model.add(layers.MaxPooling2D((2, 2)))\n",
    "model.add(layers.Flatten())\n",
    "model.add(layers.Dense(512, activation='relu'))\n",
    "model.add(layers.Dense(1, activation='sigmoid'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from keras import optimizers\n",
    "\n",
    "model.compile(loss='binary_crossentropy',\n",
    "              optimizer=optimizers.RMSprop(lr=1e-4),\n",
    "              metrics=['acc'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 901 images belonging to 2 classes.\n",
      "Found 257 images belonging to 2 classes.\n"
     ]
    }
   ],
   "source": [
    "from keras.preprocessing.image import ImageDataGenerator\n",
    "\n",
    "# All images will be rescaled by 1./255\n",
    "train_datagen = ImageDataGenerator(rescale=1./255)\n",
    "test_datagen = ImageDataGenerator(rescale=1./255)\n",
    "\n",
    "train_generator = train_datagen.flow_from_directory(\n",
    "        # This is the target directory\n",
    "        train_dir,\n",
    "        # All images will be resized to 40x160\n",
    "        target_size=(80, 400),\n",
    "        batch_size=20,\n",
    "        # Since we use binary_crossentropy loss, we need binary labels\n",
    "        class_mode='binary')\n",
    "\n",
    "validation_generator = test_datagen.flow_from_directory(\n",
    "        validation_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=20,\n",
    "        class_mode='binary')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/50\n"
     ]
    }
   ],
   "source": [
    "history = model.fit_generator(\n",
    "      train_generator,\n",
    "      steps_per_epoch=100,\n",
    "      epochs=100,\n",
    "      validation_data=validation_generator,\n",
    "      validation_steps=50)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "acc = history.history['acc']\n",
    "val_acc = history.history['val_acc']\n",
    "loss = history.history['loss']\n",
    "val_loss = history.history['val_loss']\n",
    "\n",
    "epochs = range(len(acc))\n",
    "\n",
    "plt.plot(epochs, acc, 'bo', label='Training acc')\n",
    "plt.plot(epochs, val_acc, 'b', label='Validation acc')\n",
    "plt.title('Training and validation accuracy')\n",
    "plt.legend()\n",
    "\n",
    "plt.figure()\n",
    "\n",
    "plt.plot(epochs, loss, 'bo', label='Training loss')\n",
    "plt.plot(epochs, val_loss, 'b', label='Validation loss')\n",
    "plt.title('Training and validation loss')\n",
    "plt.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#alternative model with image augmentation\n",
    "\n",
    "from keras.preprocessing.image import ImageDataGenerator\n",
    "#Let's train our network using data augmentation and dropout:\n",
    "train_datagen = ImageDataGenerator(\n",
    "    rescale=1./255,\n",
    "    rotation_range=40,\n",
    "    width_shift_range=0.2,\n",
    "    height_shift_range=0.2,\n",
    "    shear_range=0.2,\n",
    "    zoom_range=0.2,\n",
    "    horizontal_flip=True,)\n",
    "\n",
    "# Note that the validation data should not be augmented!\n",
    "test_datagen = ImageDataGenerator(rescale=1./255)\n",
    "\n",
    "train_generator = train_datagen.flow_from_directory(\n",
    "        # This is the target directory\n",
    "        train_dir,\n",
    "        # All images will be resized to 150x150\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        # Since we use binary_crossentropy loss, we need binary labels\n",
    "        class_mode='binary')#put \"categorical\" if there's more than 2 categories\n",
    "\n",
    "validation_generator = test_datagen.flow_from_directory(\n",
    "        validation_dir,\n",
    "        target_size=(80, 400),\n",
    "        batch_size=32,\n",
    "        class_mode='binary')# use \"categorical\" if there's more than 2 groups\n",
    "\n",
    "history = model.fit_generator(\n",
    "      train_generator,\n",
    "      steps_per_epoch=30,\n",
    "      epochs=100,\n",
    "      validation_data=validation_generator,\n",
    "      validation_steps=10)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
